#!/usr/bin/env bash

#check for parameters' number
if [ $# -lt 3 ];then
echo "error : liftover.sh mergefile databasefile file1 file2 ... " 1>&2
exit 1
fi

#test=`find db*`
#if [ $? -ne 0 ]; then
#echo "ce fichier n'est pas une image .jpg"
#else
#/usr/bin/convert $f -resize $geom ~/Images/thumbnails/$(basename $f .jpg)_$geom.png
#fi
#find db* > /dev/null
#if[ $? -ne 0 ];then

datefile=`date +%e%m%Y` # date ddmmyyyy

#mergefile
mergefile=$1
shift
cat $mergefile | sort -t' ' -k1,1 > merge_tmp1.txt

#databasefile
db=$1
cat $db |  awk -F" " '{print $1"-"$3,$1,$2,$6,$4,$5}' | sort -t' ' -k1,1 > "db_"$datefile".txt" #sort by chromosome and position
shift

#if [ -d "./output_liftoversh" ]; then
#else
mkdir output_liftoversh
#fi


for f in $@;do

#datafiles wellconverted
name=`basename $f .txt`
cat $f | sed 's/^chr//' | awk -F"	" '{print $1"-"$2,$4}' | sort -t' ' -k1,1 > "sort_"$name"_"$datefile".txt" #sort by chromosome and position
echo "chr-position	snpIDdata	chr	snpIDdb		freqDBa0	a0DB	a1DB" > "output_liftoversh/res_"$name"_"$datefile".txt" #header of result's file
join -t' ' -1 1 -2 1 "sort_"$name"_"$datefile".txt" "db_"$datefile".txt" | tr ' ' '	' >> "output_liftoversh/res_"$name"_"$datefile".txt"  #join files by identical chromosome-position

rm "sort_"$name"_"$datefile".txt" 
echo "see output_liftoversh/res_"$name"_"$datefile".txt"

#datafiles failed
endfailedfile=`basename ${f##*_} .txt`
failedfile="liftover_failed_"$endfailedfile
cat $failedfile".txt" | sed '/#Deleted in new/d' | cut -d"	" -f4 | uniq > "output_liftoversh/exclude_"$failedfile"_"$datefile".txt"
echo "see output_liftoversh/exclude_"$failedfile"_"$datefile".txt"

#check RsMerge
# select lines with rsID in 1000genomes database and delete "rs" prefix
cat "res_"$name"_"$datefile".txt" | egrep "	[0-9]+	rs" | sed 's/rs//' | sed 's/rs//' > temporary.txt
# search rsID 1000G in RsMerge
cut -d"	" -f4 temporary.txt | sort > listotest.txt
join -1 1 -2 1 listotest.txt merge_tmp1.txt  > "jointmp_"$name"_"$datefile".txt"
# only keep SNP 
cat "jointmp_"$name"_"$datefile".txt" | sort -t' ' -k2,2 > "jointmp2_"$name"_"$datefile".txt"
cut -d"	" -f2 temporary.txt | sort > listotest2.txt
join -1 1 -2 2 listotest2.txt "jointmp2_"$name"_"$datefile".txt" | tr ' ' '	' > "output_liftoversh/keep_"$name"_"$datefile".txt"
echo "see output_liftoversh/keep_"$name"_"$datefile".txt"

done

rm temporary.txt
rm listotest.txt
rm listotest2.txt
rm jointmp*

# command example : ./liftover.sh ../../db/RsMergeArch.bcp ../../db/NEW_1000/EUR.chrfulldata.db liftover_wellconverted_*
